<?php

namespace app\admin\controller\sales;

//use app\admin\controller\customer\Customer;
use app\common\controller\Backend;
use app\common\model\goods\Goods;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\sales\RetreatGoods;
use app\common\model\customer\Customer;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Retreat extends Backend
{
    
    /**
     * Retreat模型对象
     * @var \app\common\model\change\Retreat
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\change\Retreat;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $this->handlefilter();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['salescheckout','salesslip','customer','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['salescheckout','salesslip','customer','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','createtime','number','collectiontime','explain','abstract','operator','company','status','tax']);
                $row->visible(['salescheckout']);
				$row->getRelation('salescheckout')->visible(['number']);
				$row->visible(['salesslip']);
				$row->getRelation('salesslip')->visible(['number']);
				$row->visible(['customer']);
				$row->getRelation('customer')->visible(['nickname']);
				$row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $statuss = $this->model->retreat_status();
            foreach ($list as $k=> $v){
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $statuss[$v['status']];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function detail($ids=null){
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

        $row = $this->model->find($ids);
        if ($this->request->isAjax()) {
            $status = input('status/d',0);

            if(empty($status)){
                $this->error('状态异常');
            }
            $row = $this->model->find($ids);
            if(!$row){
                $this->error('退货单不存在');
            }
            if($row['status'] !=1){
                $this->error('状态异常');
            }
            Db::startTrans();
            try {
                $odata['status'] = $status;
                if($status == 3) {
                    //减少库存
                    $rgoods = new RetreatGoods();
                    $list = $rgoods->where(array('sales_retreat_id' => $ids))->select();

                    foreach ($list as $v) {
                        $GoodsHouseStock = new GoodsHouseStock;
                        //增加库存
                        $rinfo = $GoodsHouseStock->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();

                        $balance = $rinfo['balance']+$v['goods_num']*$v['costPrice'];
                        $GoodsHouseStock->save(
                            array(
                                'stock'=>$rinfo['stock']+$v['goods_num'],
                                'balance'=>$balance,
                                'weighting_cost'=>$balance/($rinfo['stock']+$v['goods_num'])
                            ),array(
                                'id'=>$rinfo['id']
                            )
                        );
//                    $rr = $GoodsHouseStock->reducestock($v['goods_id'], $row['storehouse_id'], $v['goods_num']);
//                        $rr = $GoodsHouseStock->addstock($v['goods_id'], $row['storehouse_id'], $v['goods_num']);
//                        if (!$rr) {
//                            $Goods = new Goods;
//                            $ginfo = $Goods->find($v['goods_id']);
//                            Db::rollback();
//                            throw new Exception($ginfo['title'] . '库存异常,请检查');
//                        }

                        $goods = new \app\common\model\goods\Goods();
                        $final_cost = $goods->getcost($v['goods_id'],$row['storehouse_id']);
                        $GoodsHouseStock = new GoodsHouseStock;
                        $stock = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);
                        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                        Db::name('goods_stock_log')->insert(array(
                            'goods_id'=>$v['goods_id'],
                            'createtime'=>time(),
                            'number'=>$row['number'],
                            'type'=>'销售退货单',
                            'source'=>9,
                            'type_id'=>$row['id'],
                            'enter_num'=>$v['goods_num'],
//                            'out_num'=>$v['goods_num'],
                            'before_num'=>$stock-$v['goods_num'],
                            'now_num'=>$stock,
                            'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                            'controller'=>'sales/retreat',
                            'admin_id'=>session('admin')['id'],
                            'group_id'=>$group['group_id'],
                            'company'=>$group['name'],
                            'operator'=>session('admin')['nickname'],
                            'final_cost'=>$final_cost,
                        ));
                    }
                }
                //驳回
                if($status == 4){
                    $RetreatGoods = new RetreatGoods;
                    $RetreatGoods->save(array('status'=>0),array('sales_retreat_id'=>$ids));
                    $type = 2;
                }
                $res = $this->model->save($odata,array('id'=>$ids));
                if($status == 2){
                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                    $custrow = Customer::find($row['customer_id']);
                    Db::name('analysis')->insert(array(
                        'is_income'=>2,
                        'source'=>6,
                        'cost'=>$row['actual_cost'],
//                        'admin_id'=>session('admin')['id'],
//                        'group_id'=>$group['group_id'],
//                        'company'=>$group['name'],
                        'admin_id'=>$row['admin_id'],
                        'group_id'=>$row['group_id'],
                        'company'=>$row['company'],
                        'operator'=>$row['operator'],
                        'source_id' => $row['id'],
                        'obj_id' => $row['customer_id'],
//                        'operator'=>session('admin')['nickname'],
                        'controller'=>'sales/retreat',
                        'settle_name'=>$custrow['company'],
                        'number'=>$row['number'],
                        'createtime'=>time(),
                        'storehouse_id' => $row['storehouse_id'],
                        'explain'=>$row['explain'],//摘要
                    ));
                    $type =1;
                }
                if(!$res){
                    Db::rollback();
                    throw new Exception('数据异常');
                }
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>$type,
                    'createtime'=>time(),
                    'controller'=>'sales/retreat',
                    'source_id'=>$ids,
                    'source'=>9,
                    'remark'=>'销售退货单',
                    'number'=>isset($row['number'])?$row['number']:'',
                ));

                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'审核成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
//        if ($this->request->isAjax()) {
//
//            $collectiontime = strtotime(input('collectiontime'));
////            $createtime = strtotime(input('createtime'));
//
//            $explain = input('explain');
//            $abstract = input('abstract');
//
//            $params = input();
//            if(!isset($params['row'])){
//                $this->error('未选择商品');
//            }
//            if(!isset($params['crow'])){
//                $this->error('未选择换货商品');
//            }
//            $sdata = $params['row'];
//            //检测库存
//            $cdata = $params['crow'];
//
//
//            foreach ($sdata as $k=> $v){
//                $ChangeGoods = new ChangeGoods();
//                $where = array(
//                    'sales_checkout_id' => $ids,
//                    'sales_slip_id' => $row['sales_slip_id'],
//                );
//                $cnum = $ChangeGoods->where($where)->sum('goods_num');//已经换货数量
//                $CheckoutGoods = new CheckoutGoods;
//                $gnum = $CheckoutGoods->where($where)->sum('goods_num');
//                if($v['goods_num']+$cnum >$gnum){
//                    $this->error('商品'.$v['goods_id'].'换货超量,已经换货'.$cnum);
//                }
//            }
//            $num = Db::name('sales_change')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
//            $saledata = array(
//                'number'=>'XT-T-'.date('Y-m-d').'-'.getnumber($num),
//                'collectiontime'=>$collectiontime,
//                'customer_id'=>$row['customer_id'],
//                'storehouse_id'=>$row['customer_id'],
//                'explain'=>$explain,
//                'abstract'=>$abstract,
//                'tax'=>$row['tax'],
//                'admin_id'=>session('admin')['id'],
//                'group_id'=>$group['group_id'],
//                'company'=>$group['name'],
//                'sales_slip_id' => $row['sales_slip_id'],
//                'operator'=>session('admin')['nickname'],
//                'sales_checkout_id' => $ids,
//            );
//            Db::startTrans();
//            try {
//                $Change = new Change();
//                $Change->save($saledata);
//                $gdata = [];
//
//                foreach ($sdata as $k => $v) {
//                    $gdata[] = array(
//                        'goods_id' => $v['goods_id'],
//                        'goods_num' => $v['goods_num'],
//                        'sale_price' => $v['sale_price'],
//                        'tax' => $v['tax'],
//                        'remark' => $v['remark'],
//                        'sales_checkout_id' => $ids,
//                        'sales_slip_id' => $row['sales_slip_id'],
//                        'sales_change_id' => $Change->id,
//                    );
//                }
//                foreach ($cdata as $v){
//                    $gdata[] = array(
//                        'goods_id' => $v['goods_id'],
//                        'goods_num' => $v['goods_num'],
//                        'sale_price' => $v['sale_price'],
//                        'tax' => $v['tax'],
//                        'remark' => $v['remark'],
//                        'sales_checkout_id' => $ids,
//                        'sales_slip_id' => $row['sales_slip_id'],
//                        'sales_change_id' => $Change->id,
//                        'type'=>2,
//                    );
//                }
//                $ChangeGoods = new ChangeGoods();
//                $ChangeGoods->saveAll($gdata);
//                Db::commit();
//                return array(
//                    'code'=>1,
//                    'msg'=>'添加成功',
//                );
//            }catch (\Exception $e) {
//                // 回滚事务
//                Db::rollback();
//                $this->error($e->getMessage());
//            }
//
//
//            exit;
//        }
        }
        $list = Db::name('sales_retreat_goods')
            ->field('g.id,goods_num,sale_price,tax,remark,title,place_origin,number,unit,specs,storehouse_id')
            ->alias('sg')
            ->where(array('sales_retreat_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();

        foreach ($list as $k => $v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['id'],$v['storehouse_id']);
        }
        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $this->assign('list',$list);
        $this->assign('row',$row);
        $arr = explode('/',$_SERVER['REQUEST_URI']);
        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }

    //采购单审核
    public function examine($ids = null){
        $status = input('status/d',0);

        if(empty($status)){
            $this->error('状态异常');
        }
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('退货单不存在');
        }
        if($row['status'] !=1){
            $this->error('状态异常');
        }
        Db::startTrans();
        try {
            $odata['status'] = $status;
            if($status == 3) {
                //增加库存
                $rgoods = new RetreatGoods();
                $list = $rgoods->where(array('sales_retreat_id' => $ids))->select();

                foreach ($list as $v) {
                    $GoodsHouseStock = new GoodsHouseStock;
//                    $rr = $GoodsHouseStock->reducestock($v['goods_id'], $row['storehouse_id'], $v['goods_num']);
//                    $rr = $GoodsHouseStock->addstock($v['goods_id'], $row['storehouse_id'], $v['goods_num']);

                    //增加库存
                    $rinfo = $GoodsHouseStock->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();

                    $balance = $rinfo['balance']+$v['goods_num']*$v['costPrice'];
                    $GoodsHouseStock->save(
                      array(
                        'stock'=>$rinfo['stock']+$v['goods_num'],
                        'balance'=>$balance,
                        'weighting_cost'=>$balance/($rinfo['stock']+$v['goods_num'])
                      ),array(
                          'id'=>$rinfo['id']
                      )
                    );
//
//                    if (!$rr) {
//                        $Goods = new Goods;
//                        $ginfo = $Goods->find($v['goods_id']);
//                        Db::rollback();
//                        throw new Exception($ginfo['title'] . '库存异常,请检查');
//                    }

                    $goods = new \app\common\model\goods\Goods();
                    $final_cost = $goods->getcost($v['goods_id'],$row['storehouse_id']);
                    $GoodsHouseStock = new GoodsHouseStock;
                    $stock = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);
                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'销售退货单',
                        'type_id'=>$row['id'],
                        'enter_num'=>$v['goods_num'],
//                            'out_num'=>$v['goods_num'],
                        'before_num'=>$stock-$v['goods_num'],
                        'now_num'=>$stock,
                        'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                        'controller'=>'sales/retreat',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'final_cost'=>$final_cost,
                    ));
                }
            }
            //驳回
            if($status == 4){
                $RetreatGoods = new RetreatGoods;
                $RetreatGoods->save(array('status'=>0),array('sales_retreat_id'=>$ids));
            }
            $res = $this->model->save($odata,array('id'=>$ids));
            if($status == 2){

                $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                $custrow = Customer::find($row['customer_id']);
                Db::name('analysis')->insert(array(
                    'is_income'=>2,
                    'source'=>6,
                    'cost'=>$row['actual_cost'],
//                    'admin_id'=>session('admin')['id'],
//                    'group_id'=>$group['group_id'],
//                    'company'=>$group['name'],
                    'admin_id'=>$row['admin_id'],
                    'group_id'=>$row['group_id'],
                    'company'=>$row['company'],
                    'operator'=>$row['operator'],
                    'source_id' => $row['id'],
                    'obj_id' => $row['customer_id'],
//                    'operator'=>session('admin')['nickname'],
                    'controller'=>'sales/retreat',
                    'settle_name'=>$custrow['company'],
                    'number'=>$row['number'],
                    'createtime'=>time(),
                    'storehouse_id' => $row['storehouse_id'],
                    'explain'=>$row['explain'],//摘要
                ));
            }
            if(!$res){
                Db::rollback();
                throw new Exception('数据异常');
            }

            Db::commit();
            return  array(
                'code'=>1,
                'msg'=>'审核成功',
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    //收货确认
    public function enter($ids = null){
        $status = input('status/d',0);
        if(empty($status)){
            $this->error('状态异常');
        }
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('退货单不存在');
        }
        if($row['status'] !=2){
            $this->error('状态异常');
        }
        Db::startTrans();
        try {
            $odata['status'] = $status;
            if($status == 3) {
                //增加库存
                $rgoods = new RetreatGoods();
                $list = $rgoods->where(array('sales_retreat_id' => $ids))->select();

                foreach ($list as $v) {
                    $GoodsHouseStock = new GoodsHouseStock;
                    //增加库存
                    $rinfo = $GoodsHouseStock->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();

                    $balance = $rinfo['balance']+$v['goods_num']*$v['costPrice'];
                    $GoodsHouseStock->save(
                        array(
                            'stock'=>$rinfo['stock']+$v['goods_num'],
                            'balance'=>$balance,
                            'weighting_cost'=>$balance/($rinfo['stock']+$v['goods_num'])
                        ),array(
                            'id'=>$rinfo['id']
                        )
                    );
//                    $rr = $GoodsHouseStock->reducestock($v['goods_id'], $row['storehouse_id'], $v['goods_num']);
//                    $rr = $GoodsHouseStock->addstock($v['goods_id'], $row['storehouse_id'], $v['goods_num']);
//                    if (!$rr) {
//                        $Goods = new Goods;
//                        $ginfo = $Goods->find($v['goods_id']);
//                        Db::rollback();
//                        throw new Exception($ginfo['title'] . '库存异常,请检查');
//                    }

                    $goods = new \app\common\model\goods\Goods();
                    $final_cost = $goods->getcost($v['goods_id'],$row['storehouse_id']);
                    $GoodsHouseStock = new GoodsHouseStock;
                    $stock = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);
                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'销售退货单',
                        'type_id'=>$row['id'],
                        'enter_num'=>$v['goods_num'],
//                            'out_num'=>$v['goods_num'],
                        'before_num'=>$stock-$v['goods_num'],
                        'now_num'=>$stock,
                        'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                        'controller'=>'sales/retreat',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'final_cost'=>$final_cost,
                    ));



                }
            }
            $res = $this->model->save($odata,array('id'=>$ids));
            if(!$res){
                Db::rollback();
                throw new Exception('数据异常');
            }
            Db::commit();
            return  array(
                'code'=>1,
                'msg'=>'审核成功',
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
}
